﻿@page "/UploadImage"

<h3>UploadImage</h3>
@inject IJSRuntime jsRuntime
@inject AntDesign.IMessageService _message

<link href="_content/AntDesign/css/ant-design-blazor.css" rel="stylesheet">
<link antblazor-css />

<InputFile id="fileInput" OnChange="UploadFiles" hidden />

<AntDesign.Upload Name="files" FileList="fileList">
    <label class="ant-btn" for="fileInput">
        <AntDesign.Icon Type="upload" />
        Upload
    </label>
</AntDesign.Upload>

<RadzenDataGrid EditMode="@editMode" @ref=grid TItem="PoiDto" AllowPaging="false" PageSize="5" AllowSorting="false"
                Data="@poiData" RowUpdate="@OnUpdateRow" Sort="@(args => Reset())" Page="@(args => Reset())" Filter="@(args => Reset())"
                ColumnWidth="200px" RowRender="@RowRender" AllowColumnResize="true" CellClick="@OnCellClick">
    <Columns>
        <RadzenDataGridColumn TItem="PoiDto" Property=@nameof(PoiDto.Guid) Title=@nameof(PoiDto.Guid) Width="120px" IsInEditMode="@IsEditing">
            <Template Context="data">
                <RadzenText Text="@(data.Guid)" />
            </Template>
        </RadzenDataGridColumn>

        <RadzenDataGridColumn TItem="PoiDto" Property=@nameof(PoiDto.Name) Title=@nameof(PoiDto.Name) Width="120px" IsInEditMode="@IsEditing">
            <Template Context="data">
                <RadzenText Text="@(data.Name)" />
            </Template>
        </RadzenDataGridColumn>

        <RadzenDataGridColumn TItem="PoiDto" Property=@nameof(PoiDto.Photo) Title=@nameof(PoiDto.Photo) Width="120px" IsInEditMode="@IsEditing">
            <Template Context="data">
                <RadzenImage Path="@data.Photo" Style="width: 100px; height: 100px;" class="rz-border-radius-2 rz-me-2" />
                <Image Width="100px" Src="@data.Photo" />
            </Template>
        </RadzenDataGridColumn>

        <RadzenDataGridColumn Width="40px" TItem="PoiDto" Property=@nameof(PoiDto.Show) Title=@nameof(PoiDto.Show) IsInEditMode="@IsEditing">
            <Template Context="data">
                <RadzenCheckBox Value="@data.Show" Name="Show" />
            </Template>
            <EditTemplate Context="data">
                <RadzenCheckBox @bind-Value=data.Show Name="Show" />
            </EditTemplate>
        </RadzenDataGridColumn>


        <RadzenDataGridColumn Width="80px" TItem="PoiDto" Filterable="false" Sortable="false" TextAlign="Radzen.TextAlign.Center" Frozen="true" FrozenPosition="FrozenColumnPosition.Right">
            <Template Context="data">
                <RadzenButton Icon="edit" ButtonStyle="Radzen.ButtonStyle.Light" Variant="Variant.Flat" Size="Radzen.ButtonSize.Medium" Click="@(args => EditRow(data))" @onclick:stopPropagation="true">
                </RadzenButton>
                <RadzenButton ButtonStyle="Radzen.ButtonStyle.Danger" Icon="delete" Variant="Variant.Flat" Shade="Shade.Lighter" Size="Radzen.ButtonSize.Medium" class="my-1 ms-1" Click="@(args => DeleteRow(data))" @onclick:stopPropagation="true">
                </RadzenButton>
            </Template>
        </RadzenDataGridColumn>

    </Columns>
</RadzenDataGrid>

<Button Text="Add" OnClick="AddRowClick" />

<!-- AntDesign -->
<script src="_content/AntDesign/js/ant-design-blazor.js"></script>
<script antblazor-js></script>

@code {

    List<AntDesign.UploadFileItem> fileList = new List<AntDesign.UploadFileItem>();


    IList<IBrowserFile> files = new List<IBrowserFile>();
    private async Task UploadFiles(InputFileChangeEventArgs args)
    {
        foreach (var file in args.GetMultipleFiles(1))
        {
            var size = file.Size;
            byte[] bytes = new byte[size];
            await file.OpenReadStream(size).ReadAsync(bytes, 0, bytes.Length);
        }
        // //TODO upload the files to the server
        // var file = files.FirstOrDefault();
        // var size = file.Size;
        // byte[] bytes = new byte[size];
        // file.OpenReadStream(size).ReadAsync(bytes, 0, bytes.Length);
        // var base64 = Convert.ToBase64String(bytes);
        fileList = files.Select(file => new AntDesign.UploadFileItem { FileName = file.Name, Size = file.Size }).ToList();
    }


    #region

    DataGridEditMode editMode = DataGridEditMode.Single;
    public RadzenDataGrid<PoiDto> grid;
    public string columnEditing;

    public List<PoiDto> poiData = new List<PoiDto>();
    List<PoiDto> ordersToUpdate = new List<PoiDto>();

    public string base64 = "";

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        poiData = new List<PoiDto>()
        {
            new PoiDto
            {
                Name="Top",
                   Show=true,
                    Photo=base64,
            }
        };
    }


    public bool IsEditing(string columnName, PoiDto data)
    {
        return columnEditing == columnName && ordersToUpdate.Contains(data);
    }


    public void OnCellClick(DataGridCellMouseEventArgs<PoiDto> args)
    {
        columnEditing = args.Column.Property;
        if (columnEditing != nameof(PoiDto.Show))
            return;

        if (ordersToUpdate.Any())
        {
            OnUpdateRow(ordersToUpdate.First());
        }
        EditRow(args.Data);
    }

    public void Reset(PoiDto data = null)
    {
        if (data != null)
        {
            ordersToUpdate.Remove(data);
        }
        else
        {
            ordersToUpdate.Clear();
        }
    }

    public async Task EditRow(PoiDto data)
    {
        Reset();

        ordersToUpdate.Add(data);
        await grid.EditRow(data);
    }

    public void OnUpdateRow(PoiDto data)
    {
        Reset(data);
    }

    public async Task DeleteRow(PoiDto data)
    {
        Reset(data);
        if (poiData.Contains(data))
        {
            poiData.Remove(data);
            await grid.Reload();
        }
        else
        {
            grid.CancelEditRow(data);
            await grid.Reload();
        }
    }

    public async Task AddRowClick()
    {
        poiData.Add(new PoiDto
            {
                Guid = Guid.NewGuid().ToString(),
                Name = "Bttom",
                Show = true,
                Photo = base64,
            });
        grid.Reload();
    }

    public async Task ClearClick()
    {
        poiData = new List<PoiDto>();
    }


    async Task SaveRow(PoiDto order)
    {
        await grid.UpdateRow(order);
        var poiOtherData = poiData.FindAll(s => !s.Equals(order)).ToList();
    }

    void CancelEdit(PoiDto order)
    {
        Reset(order);

        grid.CancelEditRow(order);
    }

    PoiDto draggedPoiItem;

    void RowRender(RowRenderEventArgs<PoiDto> args)
    {
        args.Attributes.Add("title", "Drag row to reorder");
        args.Attributes.Add("style", "cursor:grab");
        args.Attributes.Add("draggable", "true");
        args.Attributes.Add("ondragover", "event.preventDefault();event.target.closest('.rz-data-row').classList.add('my-class')");
        args.Attributes.Add("ondragleave", "event.target.closest('.rz-data-row').classList.remove('my-class')");
        args.Attributes.Add("ondragstart", EventCallback.Factory.Create<DragEventArgs>(this, () => draggedPoiItem = args.Data));
        args.Attributes.Add("ondrop", EventCallback.Factory.Create<DragEventArgs>(this, async () =>
        {
            var draggedIndex = poiData.IndexOf(draggedPoiItem);
            var droppedIndex = poiData.IndexOf(args.Data);
            poiData.Remove(draggedPoiItem);
            poiData.Insert(draggedIndex <= droppedIndex ? droppedIndex++ : droppedIndex, draggedPoiItem);

            jsRuntime.InvokeVoidAsync("eval", $"document.querySelector('.my-class').classList.remove('my-class')");
            await grid.Reload();
        }));
    }

    public class PoiDto
    {
        public string Guid { get; set; }

        public string Name { get; set; }

        public bool Show { get; set; }
        public string Photo { get; set; }
    }

    #endregion

}
